﻿using ET.Monitor.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebAPI.App_Code;
using System.Web.Http.Cors;

namespace ET.Monitor.Web.Api
{
    public class ScreenController : ApiController
    {
        // GET: Screen

        StringHelper sh = new StringHelper();

        #region 登录
        [HttpPost]
        public HttpResponseMessage CheckLogin()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象

            string userName = request.Form["name"];
            string password = request.Form["pwd"];
            try
            {
                PersonnelModel pm = new PersonnelModel(userName, password);
                object ck = pm.ObjCheck;
                object obj = new
                {
                    judge = ck.ToString(),
                    uid = userName
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：CheckLogin");
                sh.WriteLog("获取到参数：name=" + userName);
                sh.WriteLog("获取到参数：pwd=" + password);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 集团首页

        #region 集团数据
        [HttpPost]
        public HttpResponseMessage GetCliqueInfo()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string id = request.Form["id"];
            string userId = request.Form["userId"];
            try
            {
                CliqueModel cm = new CliqueModel(id);

                object realPower = cm.ObjPower;
                object power = double.IsNaN(Convert.ToDouble(realPower)) ? null : realPower;

                double totalRL = cm.SumRL;
                object rl = double.IsNaN(totalRL) ? null : totalRL.ToString();

                double totalDL = cm.DlSumDL;
                object sumDL = double.IsNaN(totalDL) ? null : totalDL.ToString();

                StationModel sm = new StationModel(id);
                object dayYearDL = null;
                double dayDL = sm.RealDL;

                dayDL = sh.GetDouble(dayDL, 2);
                if (DateTime.Now.Month == 1 && DateTime.Now.Day == 1)
                    dayYearDL = dayDL;
                else
                {
                    cm = new CliqueModel(Convert.ToDateTime(DateTime.Now.ToString("yyyy-1-1 0:00:00")), Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59")));
                    dayYearDL = sh.GetDouble(cm.YearDL, 2) + dayDL;
                }
                //负荷趋势
                cm = new CliqueModel(id, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 0:00:00")), DateTime.Now, 300);
                double[] powerLine = cm.Line;
                double[] line = null;
                if (powerLine != null)
                {
                    line = new double[powerLine.Length];
                    for (int i = 0; i < powerLine.Length; i++)
                    {
                        line[i] = sh.GetDouble(powerLine[i], 2);
                    }
                }

                cm = new CliqueModel(Convert.ToDateTime(DateTime.Now.AddMonths(-12).ToString("yyyy-MM-1 0:00:00")), DateTime.Now);
                //电量趋势
                DataTable dtDL = cm.DtTotalMonthDL;
                string[] strDay = null;
                double[] chart = null;
                if (dtDL != null && dtDL.Rows.Count > 0)
                {
                    chart = new double[dtDL.Rows.Count];
                    strDay = new string[dtDL.Rows.Count];
                    for (int i = 0; i < dtDL.Rows.Count; i++)
                    {
                        chart[i] = Convert.ToDouble(dtDL.Rows[i][2].ToString());
                        strDay[i] = dtDL.Rows[i][0] + "-" + dtDL.Rows[i][1];
                    }
                }

                OrgModel om = new OrgModel(userId);
                DataTable dtStation = om.AllOrgStationInfo;          //所有用户电站      
                string[] stationID = dtStation.AsEnumerable().Select(x => x["T_ORGID"].ToString()).ToArray();
                string[] stationName = dtStation.AsEnumerable().Select(x => x["T_PLANTDESC"].ToString()).ToArray();
                sm = new StationModel("'" + string.Join("','", stationID) + "'");
                DataTable dtRL = sm.AllRL;

                IList<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < stationID.Length; i++)
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("id", stationID[i]);
                    ht.Add("name", stationName[i]);
                    DataRow[] drRL = dtRL.Select("T_ORGID ='" + stationID[i] + "'", "t_time desc");
                    if (drRL.Length > 0)
                        ht.Add("rl", drRL[0]["D_RL"]);
                    else
                        ht.Add("rl", null);
                    list.Add(ht);
                }


                object obj = new
                {
                    power = power,
                    rl = rl,
                    dayDL = dayDL,
                    yearDL = dayYearDL,
                    sumDL = sumDL,
                    line = line,
                    chart = chart,
                    chartDay = strDay
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetCliqueInfo");
                sh.WriteLog("获取到参数：id=" + id);
                sh.WriteLog("获取到参数：userId=" + userId);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 电站数据
        [HttpPost]
        public HttpResponseMessage GetStationList()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string userId = request.Form["userId"];
            string id = request.Form["privinceId"];
            try
            {
                OrgModel om = new OrgModel(userId);
                DataTable dtStation = om.AllOrgStationInfo;          //所有用户电站       
                DataTable dtCity = om.DtCity;

                string[] cityID = dtCity.AsEnumerable().Where(T => T.Field<string>("T_PARENTID") == id).Select(x => x["T_CITYID"].ToString()).ToArray();
                List<string> listCityID = new List<string>();
                for (int i = 0; i < cityID.Length; i++)
                {
                    listCityID.Add(cityID[i]);
                }

                string[] stationID = dtStation.AsEnumerable().Where(T => listCityID.Contains(T.Field<string>("T_CITYID"))).Select(x => x["T_ORGID"].ToString()).ToArray();
                string[] stationName = dtStation.AsEnumerable().Where(T => listCityID.Contains(T.Field<string>("T_CITYID"))).Select(x => x["T_PLANTDESC"].ToString()).ToArray();
                StationModel sm = new StationModel("'" + string.Join("','", stationID) + "'", "负荷,电量".Split(','));
                List<double[]> listValues = sm.RealVal;

                IList<Hashtable> listStation = new List<Hashtable>();
                for (int i = 0; i < stationID.Length; i++)
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("id", stationID[i]);
                    ht.Add("name", stationName[i]);
                    if (double.IsNaN(listValues[0][i]))
                        ht.Add("power", null);
                    else
                        ht.Add("power", listValues[0][i]);

                    if (double.IsNaN(listValues[1][i]))
                        ht.Add("dl", null);
                    else
                        ht.Add("dl", listValues[1][i]);
                    listStation.Add(ht);
                }

                object obj = new
                {
                    data = listStation
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetStationList");
                sh.WriteLog("获取到参数：id=" + id);
                sh.WriteLog("获取到参数：userId=" + userId);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion

        #region 电站首页

        #region 电站信息
        [HttpPost]
        public HttpResponseMessage GetStationInfo()
        {
            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            string id = request.Form["stationId"];
            try
            {
                StationModel sm = new StationModel(id);
                double rl = sm.RL;
                double count = sm.InverterCount;

                double bl = sm.SumDL;

                double dlJm = bl / 1000 * 0.36;
                double dlEyht = bl / 1000 * 0.997;
                double dlSlkf = bl / 1000 * 1.1546;

                sm = new StationModel("'" + id + "'", "负荷,电量,辐照度".Split(','));

                List<double[]> listValues = sm.RealVal;
                double power = listValues[0][0];
                double dl = listValues[1][0];
                double irradiance = listValues[2][0];
                double yearDL = 0;
                double monthDL = 0;

                if (!double.IsNaN(Convert.ToDouble(dl)) && Convert.ToDouble(dl) != -99999)
                {
                    if (DateTime.Now.Month == 1 && DateTime.Now.Day == 1) yearDL = dl;
                    else
                    {
                        if (DateTime.Now.Day == 1) monthDL = dl;
                        else
                        {
                            sm = new StationModel(id, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-1 0:00:00")), Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59")));
                            monthDL = sm.DL + dl;
                        }
                        sm = new StationModel(id, Convert.ToDateTime(DateTime.Now.ToString("yyyy-1-1 0:00:00")), Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59")));
                        yearDL = sm.DL + dl;
                    }
                }
                sm = new StationModel(id, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 0:00:00")), DateTime.Now, 5 * 60);
                double[] line = sm.Line;

                object obj = new
                {
                    power = power,
                    dayDL = dl,
                    monthDL = monthDL,
                    yearDL = yearDL,
                    rl = rl,
                    count = count,
                    fzd = irradiance,
                    line = line,
                    eyht = dlEyht,
                    jm = dlJm,
                    kf = dlSlkf
                };
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetStationInfo");
                sh.WriteLog("获取到参数：id=" + id);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 逆变器信息
        [HttpPost]
        public HttpResponseMessage GetInverterList()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象

            string id = request.Form["stationId"];
            try
            {
                StationModel sm = new StationModel(id);
                DataTable dtInverter = sm.DtInverters;

                string[] inverterID = dtInverter.AsEnumerable().Select(T => T["T_UNITID"].ToString()).ToArray();
                string[] inverterName = dtInverter.AsEnumerable().Select(T => T["T_UNITDESC_CN"].ToString()).ToArray();

                InverterModel im = new InverterModel("'" + string.Join("','", inverterID) + "'", "负荷,电量".Split(','));
                List<double[]> listVal = im.List;

                IList<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < inverterID.Length; i++)
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("id", inverterID[i]);
                    ht.Add("name", inverterName[i]);
                    ht.Add("power", listVal[0][i]);
                    ht.Add("dl", listVal[1][i]);
                    list.Add(ht);
                }

                object obj = new
                {
                    data = list
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetInverterList");
                sh.WriteLog("获取到参数：id=" + id);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 逆变器详细信息
        [HttpPost]
        public HttpResponseMessage GetInverterInfo()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象

            string id = request.Form["inverterId"];
            try
            {
                InverterModel im = new InverterModel(id);
                ArrayList listInverter = im.ListInverter;

                string[] pointNames = (string[])listInverter[0];
                string[] points = (string[])listInverter[1];

                PointModel pm = new PointModel(points);
                double[] pointVals = (double[])pm.RealValArray;


                object obj = new
                {
                    columns = pointNames,
                    values = pointVals
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetInverterInfo");
                sh.WriteLog("获取到参数：id=" + id);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion

        #region 报表

        #region 年报
        [HttpPost]
        public HttpResponseMessage GetReportYear()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            DateTime st = Convert.ToDateTime(request.Form["st"]);
            DateTime et = Convert.ToDateTime(request.Form["et"]);
            string userId = request.Form["userId"];
            try
            {
                OrgModel om = new OrgModel(userId);
                DataTable dtStation = om.AllOrgStationInfo;          //所有用户电站       
                CliqueModel cm = new CliqueModel(Convert.ToDateTime(st), Convert.ToDateTime(et));
                DataTable dtDL = cm.DtDLMonthTotal;

                IList<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < dtStation.Rows.Count; i++)
                {
                    string[] val = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["合计"].ToString()).ToArray();
                    string[] strYear = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["年"].ToString()).ToArray();
                    string[] strMonth = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["月"].ToString()).ToArray();

                    for (int k = 0; k < val.Length; k++)
                    {
                        Hashtable ht = new Hashtable();
                        ht.Add("stationID", dtStation.Rows[i]["T_ORGID"]);
                        ht.Add("stationName", dtStation.Rows[i]["T_PLANTDESC"]);
                        ht.Add("time", strYear[k] + "-" + strMonth[k]);
                        ht.Add("val", val[k]);
                        list.Add(ht);
                    }
                }

                object obj = new
                {
                    data = list
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetReportYear");
                sh.WriteLog("获取到参数：st=" + st);
                sh.WriteLog("获取到参数：et=" + et);
                sh.WriteLog("获取到参数：userId=" + userId);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 月报
        [HttpPost]
        public HttpResponseMessage GetReportMonth()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            DateTime st = Convert.ToDateTime(request.Form["st"]);
            DateTime et = Convert.ToDateTime(request.Form["et"]);
            string userId = request.Form["userId"];
            try
            {
                OrgModel om = new OrgModel(userId);
                DataTable dtStation = om.AllOrgStationInfo;          //所有用户电站       
                CliqueModel cm = new CliqueModel(Convert.ToDateTime(st), Convert.ToDateTime(et));
                DataTable dtDL = cm.DtDLDayTotal;

                IList<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < dtStation.Rows.Count; i++)
                {
                    string[] val = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["合计"].ToString()).ToArray();
                    string[] strYear = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["年"].ToString()).ToArray();
                    string[] strMonth = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["月"].ToString()).ToArray();
                    string[] strDay = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["日"].ToString()).ToArray();


                    for (int k = 0; k < val.Length; k++)
                    {
                        Hashtable ht = new Hashtable();
                        ht.Add("stationID", dtStation.Rows[i]["T_ORGID"]);
                        ht.Add("stationName", dtStation.Rows[i]["T_PLANTDESC"]);
                        ht.Add("time", strYear[k] + "-" + strMonth[k] + "-" + strDay[k]);
                        ht.Add("val", val[k]);
                        list.Add(ht);
                    }
                }

                object obj = new
                {
                    data = list
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetReportMonth");
                sh.WriteLog("获取到参数：st=" + st);
                sh.WriteLog("获取到参数：et=" + et);
                sh.WriteLog("获取到参数：userId=" + userId);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #region 日报
        [HttpPost]
        public HttpResponseMessage GetReportDay()
        {

            HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
            HttpRequestBase request = context.Request;//定义传统request对象
            DateTime st = Convert.ToDateTime(request.Form["st"]);
            DateTime et = Convert.ToDateTime(request.Form["et"]);
            string userId = request.Form["userId"];
            try
            {
                OrgModel om = new OrgModel(userId);
                DataTable dtStation = om.AllOrgStationInfo;          //所有用户电站       
                CliqueModel cm = new CliqueModel(Convert.ToDateTime(st), Convert.ToDateTime(et));
                DataTable dtDL = cm.DtDLHourTotal;

                IList<Hashtable> list = new List<Hashtable>();
                for (int i = 0; i < dtStation.Rows.Count; i++)
                {
                    string[] val = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["合计"].ToString()).ToArray();
                    string[] strYear = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["年"].ToString()).ToArray();
                    string[] strMonth = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["月"].ToString()).ToArray();
                    string[] strDay = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["日"].ToString()).ToArray();
                    string[] strHour = dtDL.AsEnumerable().Where(T => T.Field<string>("T_ORGID") == dtStation.Rows[i]["T_ORGID"].ToString()).Select(T => T["小时"].ToString()).ToArray();


                    for (int k = 0; k < val.Length; k++)
                    {
                        Hashtable ht = new Hashtable();
                        ht.Add("stationID", dtStation.Rows[i]["T_ORGID"]);
                        ht.Add("stationName", dtStation.Rows[i]["T_PLANTDESC"]);
                        ht.Add("time", strYear[k] + "-" + strMonth[k] + "-" + strDay[k] + " " + strHour[k] + ":00:00");
                        ht.Add("val", val[k]);
                        list.Add(ht);
                    }
                }

                object obj = new
                {
                    data = list
                };

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string str = serializer.Serialize(obj);
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
            catch (Exception ex)
            {
                sh.WriteLog("异常===========================");
                sh.WriteLog("调用方法名称：GetReportDay");
                sh.WriteLog("获取到参数：st=" + st);
                sh.WriteLog("获取到参数：et=" + et);
                sh.WriteLog("获取到参数：userId=" + userId);
                sh.WriteLog("异常内容：" + ex.Message);
                sh.WriteLog("异常===========================");
                return null;
            }
        }
        #endregion

        #endregion
    }
}